<template>
	<div class="own-app-container">
		<div class="flex justify-between align-center flex-no-wrap">
			<el-divider content-position="left"><span class="text-lg text-bold">配置项</span></el-divider>
			<PointPlanSettingPrevChooseDateRange dialogTitle="增加配置" buttonText="增加配置"
				:buttonClass="['margin-lr-sm', 'flex-none']" buttonIcon="el-icon-circle-plus-outline" hasExcludeSelect 
				:daterangeList.sync="daterangeList" @add-setting="addSet" />
		</div>

		<PointPlanSettingShowSetting ref="PointPlanSettingShowSetting" :useEditSetting="useEditSetting" 
		:settings.sync="settings" @add-set="showAddSet" @add-build="showAddBuild"  @add-point="showAddPoint"/>

		<PointPlanSettingEditSetting ref="PointPlanSettingEditSetting" @confirm-setting="completeSetting">
		</PointPlanSettingEditSetting>
	</div>
</template>

<script>
	import {
		isArray,
		isObject,
		isTrue,
		isFunction,
		generateUUID,
		accMul,
		accAdd,
		formatDate,
		getTimeSlot
	} from '@/utils/util.js'
	import common from '@/utils/common.js';
	import {
		Message
	} from 'element-ui'
	import {
		cloneDeep
	} from 'lodash'
	import PointPlanSettingEditSetting from '@/components/PointPlanSetting/editSetting'
	import PointPlanSettingShowSetting from '@/components/PointPlanSetting/showSetting'
	import PointPlanSettingPrevChooseDateRange from '@/components/PointPlanSetting/prevChooseDateRange'
	export default {
		name: 'PointPlanSettingEditPlan',
		components: {
			PointPlanSettingEditSetting,
			PointPlanSettingShowSetting,
			PointPlanSettingPrevChooseDateRange
		},
		beforeDestroy() {

		},
		// beforeRouteLeave(to, from, next) {
		// 	this.$destroy();
		// 	next();
		// },
		props: {
			settings: {
				type: Array,
				default: () => []
			},
			useEditSetting:{
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				daterangeList: [], // 配置项时间段

				prevPage: '',
				firstAdd: false,

				// 客户列表
				customerList: [],
				// 编辑框loading
				dialogCULoading: false,
				saleTyes: [],

				// 校验规则
				cuRules: {
					'name': [{
						required: true,
						message: '请输入名称',
						trigger: 'blur'
					}],
					'customer_id': [{
						required: true,
						message: '请选择客户',
						trigger: 'blur'
					}]
				},
				view: {
					name: 'point_plan_edit_page'
				},

				// settings: this.settingsProp || [],
			}
		},
		mounted() {
			this.prevPage = this.$route.query.prevPage;
			if(!!this.useEditSetting){
				this.firstAdd = isTrue(this.$route.query.firstAdd) || false;
				if (!!this.firstAdd) {
					this.firstAdd = false;
					this.$refs.PointPlanSettingEditSetting.showAdd({
						dateRange: [this.$route.query.start_at, this.$route.query.end_at]
					});
				}
			}
		},
		watch: {
			// settingsProp: { //深度监听，可监听到对象、数组的变化
			// 	handler(val, oldVal) {
			// 		this.settings = JSON.parse(JSON.stringify(val))
			// 	},
			// 	deep: true //true 深度监听
			// },
			settings: { //深度监听，可监听到对象、数组的变化
				handler(val, oldVal) {
					this.daterangeList = (val || []).map(set => {
						return {
							id: set.id,
							name: set.dateRange[0].substring(0, 10) + ' ~ ' + set.dateRange[1].substring(0, 10)
						}
					});
					this.$emit('update:settings', val);
				},
				deep: true //true 深度监听
			}
		},
		methods: {
			calSetSum(){
				this.$refs.PointPlanSettingShowSetting.calSetSum();
			},
			// 创建方案
			addSet({
				dateRange,
				excludeDateRangeIds
			}) {
				const that = this;
				let params = {
					dateRange
				};
				if ((excludeDateRangeIds || []).length > 0) {
					let deviceIds = [];
					that.settings.forEach(set => {
						if (excludeDateRangeIds.indexOf(set.id) > -1) {
							const keys = Object.keys(set.to);
							(keys || []).forEach(key => {
								deviceIds = [...deviceIds, ...(set.to[key] || []).map(device => (device
									.id))];
							});
						}
					});
					if (deviceIds.length > 0) {
						params.outPointIds = deviceIds;
					}
				}
				if(!!that.useEditSetting){
					that.$refs.PointPlanSettingEditSetting.showAdd(params);
				}else{
					that.$emit('add-set', params);
				}
			},
			showAddSet(params){
				const that = this;
				that.$emit('add-set', params);
			},
			showAddBuild(params){
				const that = this;
				that.$emit('add-build', params);
			},
			showAddPoint(params){
				const that = this;
				that.$emit('add-point', params);
			},
			// 增加配置回调
			completeSetting(set) {
				const that = this;
				that.settings.push(Object.assign({}, set, {
					canEditDateRange: true
				}))
			},
			// 保存成新方案/修改保存时，需要对
			validSetBySaveAsNew(){
				const that = this;
				
			},
			// 校验时间段冲抵诶情况下的点位冲突
			validSettingMixDateRangeAndDeviceSame(){
				const that = this;
				let result = {
					code: 0,
					error: {}
				};
				let mixSet = {};
				const sets = (that.settings || []);
				sets.forEach((set1, index1) => {
					sets.forEach((set2, index2) => {
						if ((set1.id !== set2.id) && (!mixSet[index2+'_'+index1]) && ((set1.dateRange[0] <= set2.dateRange[0] && set1.dateRange[1] >= set2.dateRange[1])
						|| (set1.dateRange[0] >= set2.dateRange[0] && set1.dateRange[1] <= set2.dateRange[1])
						|| (set1.dateRange[0] >= set2.dateRange[0] && set1.dateRange[0] <= set2.dateRange[1])
						|| (set1.dateRange[1] >= set2.dateRange[0] && set1.dateRange[1] <= set2.dateRange[1])))
						{
							mixSet[index1+'_'+index2] = {
								a: {
									set: set1,
									index: index1,
								},
								b: {
									set: set2,
									index: index2,
								}
							};
						}
					});
				});
				const mixKeys = Object.keys(mixSet) || [];
				mixKeys.forEach(mixKey => {
					const group = mixSet[mixKey];
					const key1 = Object.keys(group.a.set.to);
					let dMap1 = new Map();
					(key1 || []).forEach(key => {
						const devices = group.a.set.to[key] || [];
						devices.forEach(d => {
							dMap1.set(parseInt(d.id), d);
						});
						
					});
					
					let buildingMap = new Map();
					let pointMap = new Map();
					(group.b.set.buildings || []).forEach(b => {
						buildingMap.set(parseInt(b.id), b);
					});
					(group.b.set.pointTypes || []).forEach(p => {
						pointMap.set(parseInt(p.id), p);
					});
					
					const key2 = Object.keys(group.b.set.to);
					(key2 || []).forEach(key => {
						const devices = group.b.set.to[key] || [];
						devices.forEach(d => {
							if(!!dMap1.get(parseInt(d.id))){
								result.code = 1;
								let err = result.error[group.a.index+'_'+group.b.index] || [];
								err.push(Object.assign(d, {
									point_type: pointMap.get(parseInt(d.point_type_id)).name,
									building: buildingMap.get(parseInt(d.building_area_id)).name,
								}));
								result.error[group.a.index+'_'+group.b.index] = err;
							}
						});
					});
				});
				return result;
			},
			// 组装保存数据结构
			getPointPlanData(type = 1) {
				const that = this;

				let old_set = [];
				let returnData = {
					type: type,
					settings: [],
					old_settings: ''
				};
				(that.settings || []).forEach(set => {
					let olsSet_to = {};
					let olsSet_uuid = {};
					let olsSet_to_exact = {};

					let buildMap = new Map();
					(set.buildings || []).forEach(b => {
						buildMap.set('' + b.id, b);
					});

					let pointMap = new Map();
					(set.pointTypes || []).forEach(b => {
						pointMap.set('' + b.id, b);
					});

					const set_uuid = generateUUID();
					const keys = Object.keys(set.to);
					let set_point_list = [];
					let all_device_ids = [];
					(keys || []).filter(key => {
						return (set.to[key] || []).length > 0;
					}).forEach(key => {
						const b_p = key.split('_');
						const sp_uuid = generateUUID();

						olsSet_to[key] = (set.to[key] || []).length;
						olsSet_uuid[key] = sp_uuid;
						olsSet_to_exact[key] = set.to[key].map(d => {
							return Object.assign({}, d, {
								media_type: pointMap.get(''+d.point_type_id).name,
								building_area: buildMap.get(''+d.building_area_id).name,
								media_type_id: d.point_type_id,
								media_type_pid: d.point_type_pid
							});
						});
						
						let temp_ds = set.to[key].map(device => {
							return {
								device_id: device.id,
								qrcode: device.qrcode
							}
						});
						all_device_ids = [...all_device_ids, ...(temp_ds || []).map(d => (d.device_id))];
						set_point_list.push({
							uuid: sp_uuid,
							building_area_id: b_p[0],
							point_type_id: b_p[1],
							num: (set.to[key] || []).length,
							device_list: temp_ds
						});


					})

					returnData.settings.push({
						uuid: set_uuid,
						start_at: set.dateRange[0],
						end_at: set.dateRange[1],
						set_json: JSON.stringify(Object.assign({}, set, {
							id: set_uuid,
							all_device_ids: all_device_ids
						})),
						set_point_list: set_point_list
					});
					old_set.push({
						to: olsSet_to,
						uuid: olsSet_uuid,
						to_exact: olsSet_to_exact,
						date_range: set.dateRange,
						point_types: set.pointTypes,
						building_areas: set.buildings
					});
				});
				
				returnData.old_settings = JSON.stringify(old_set);

				return returnData;
			}
		}
	}
</script>

<style scoped lang="scss">
	.app-container {
		/deep/.card-header {
			height: 30px;
			line-height: 30px;
			clear: both;
		}

		/deep/.el-table {
			.choosed-data {
				background-color: #e9f9ff
			}

			.out-data {
				background-color: #faecec;
			}

			.choosed-data th {
				background-color: #e9f9ff;
			}

			.out-data th {
				background-color: #faecec;
			}

			&.choosed-data-table .el-table__footer-wrapper {
				font-size: 15px;
				font-weight: bold;

				.el-table__footer td {
					background-color: #e9f9ff;
				}
			}

			&.choosed-data-table .el-table__fixed-footer-wrapper tbody td {
				background-color: #e9f9ff;
			}

			&.out-data-table .el-table__footer-wrapper {
				font-size: 15px;
				font-weight: bold;

				.el-table__footer td {
					background-color: #faecec;
				}
			}

			&.out-data-table .el-table__fixed-footer-wrapper tbody td {
				background-color: #faecec;
			}
		}
	}
</style>
